package com.dabai.applicationmanager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dabai.applicationmanager.adapter.AppAdapter;
import com.dabai.applicationmanager.bean.AppBaseInfo;
import com.dabai.applicationmanager.databinding.ActivityMainBinding;
import com.dabai.applicationmanager.dialog.TipAlertDialog;
import com.dabai.applicationmanager.impl.OnCompleteListener;
import com.dabai.applicationmanager.shizuku.Shell;
import com.dabai.applicationmanager.shizuku.ShizukuShell;
import com.dabai.applicationmanager.sort.AppByLastUpdate;
import com.dabai.applicationmanager.sort.AppByName;
import com.dabai.applicationmanager.sort.AppBySize;
import com.dabai.applicationmanager.sort.AppByTargetApi;
import com.dabai.applicationmanager.ui.AppDetailsActivity;
import com.dabai.applicationmanager.ui.SettingsActivity;
import com.dabai.applicationmanager.ui.SmallProgramActivity;
import com.dabai.applicationmanager.utils.OtherUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.ShareUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.SharedPreferencesUtils;
import com.dabai.dbutils.utils.ShellUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.uitools.base.BaseAppCompatActivity;
import com.dabai.uitools.utils.ViewUtils;
import com.github.promeg.pinyinhelper.Pinyin;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;
import com.wyt.searchbox.SearchFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.zhanghai.android.appiconloader.AppIconLoader;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;




public class MainActivity extends BaseAppCompatActivity {

    ActivityMainBinding amb;
    Context context;

    private AppAdapter appAdapter;
    private ArrayList<AppBaseInfo> appBaseInfo;
    private List<PackageInfo> packageInfos;
    private ArrayList<AppBaseInfo> appBaseInflows;

    NotificationManager notificationManager;
    private NotificationCompat.Builder notification;
    private SearchFragment searchFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        amb = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(amb.getRoot());

        context = this;

        SharedPreferencesBasicUse.init(context);

        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DBToast.showText(context, "无储存权限，不能提取到外部目录。", false);
                    }
                });


        TipAlertDialog.init(context);

        amb.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        amb.recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));

        new FastScrollerBuilder(amb.recyclerView).setPopupStyle(textView -> {
            textView.setBackgroundColor(getResources().getColor(R.color.teal_700));
            textView.setTextColor(Color.WHITE);
            textView.setTextSize(18f);
            textView.setPadding(30,30,300,30);
        }).build();

        refreshList("");

        amb.swipeRefreshLayout.setOnRefreshListener(() -> refreshList(""));
        amb.swipeRefreshLayout.setColorSchemeColors(getColor(R.color.teal_700));

        if (
                SharedPreferencesUtils.getDefaultSharedPreferences(context)
                        .getBoolean("notificationBarSchedule", true)) {
            initNotification();
        }

        searchFragment = SearchFragment.newInstance();
        searchFragment.setOnSearchClickListener(this::refreshList);

    }


    /**
     * init通知
     */
    public void initNotification() {

        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notification = new NotificationCompat.Builder(context, "extract_progress")
                .setSmallIcon(R.drawable.ic_round_android_24)
                .setContentTitle("操作进度")
                .setContentText("正在执行")
                .setProgress(100, 0, false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //通知 强度
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("extract_progress", "执行进度", importance);
            notificationManager.createNotificationChannel(channel);
        }

    }


    /**
     * 刷新列表
     */
    public void refreshList(String keyword) {
        amb.swipeRefreshLayout.setRefreshing(false);

        int mode;

        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("revealAllApplication", false)) {
            mode = 0;
        } else {
            mode = 1;
        }

        new Thread(() -> {

            switch (mode) {
                case 0:
                    runOnUiThread(() -> TipAlertDialog.getInstance(context).showTipLayout("正在加载全部应用"));
                    packageInfos = AppUtils.getAllInstalledPackages(context);
                    break;
                case 1:
                    runOnUiThread(() -> TipAlertDialog.getInstance(context).showTipLayout("正在加载用户应用列表"));
                    packageInfos = AppUtils.getUserInstalledPackages(context);
                    break;
            }

            appBaseInfo = new ArrayList<>();

            AppIconLoader appIconLoader = new AppIconLoader(130, true, context);
            PackageManager packageManager = this.getPackageManager();


            for (PackageInfo packageInfo : packageInfos) {

                    ApplicationInfo applicationInfo = packageInfo.applicationInfo;
                    String appName = packageManager.getApplicationLabel(applicationInfo).toString();

                    if (appName.contains(keyword)) {

                        AppBaseInfo appInfo = new AppBaseInfo();

                        appInfo.setName(appName);
                        appInfo.setPackageName(packageInfo.packageName);
                        appInfo.setVersion(packageInfo.versionName);
                        appInfo.setVersionCode(packageInfo.versionCode + "");
                        appInfo.setPath(packageInfo.applicationInfo.publicSourceDir);


                        switch (OtherUtils.getSortWay(context)) {
                            case 2:
                                appInfo.setLastUpdate(packageInfo.lastUpdateTime);
                                break;
                            case 4:
                                appInfo.setTargetApi(packageInfo.applicationInfo.targetSdkVersion);
                                break;
                        }
                        appInfo.setSize(new File(packageInfo.applicationInfo.publicSourceDir).length());
                        appInfo.setNameSort(Pinyin.toPinyin(appName.charAt(0)).toUpperCase());


                        if (AppUtils.isFreeze(context, packageInfo.packageName)) {
                            appInfo.setFreeze(true);
                        }

                        try {
                            appInfo.setIcon(appIconLoader.loadIcon(packageInfo.applicationInfo));
                        } catch (Exception e) {
                            appInfo.setIcon(ViewUtils.drawableToBitmap(packageManager.getApplicationIcon(applicationInfo)));
                        }

                        appBaseInfo.add(appInfo);
                    }

                }

            switch (OtherUtils.getSortWay(context)) {
                case 1:
                    Collections.sort(appBaseInfo,new AppByName(true));
                    break;
                case 2:
                    Collections.sort(appBaseInfo,new AppByLastUpdate(false));
                    break;
                case 3:
                    Collections.sort(appBaseInfo,new AppBySize(false));
                    break;
                case 4:
                    Collections.sort(appBaseInfo,new AppByTargetApi(false));
                    break;
            }

            appAdapter = new AppAdapter(appBaseInfo);
            appAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);

            // 设置点击事件
            appAdapter.setOnItemClickListener((adapter, view, position) -> {

                //多选模式 , 拦截 之前的单击事件
                if (appAdapter.isSelect()) {
                    CheckBox checkBox = (CheckBox) adapter.getViewByPosition(position, R.id.checkBox);

                    if (checkBox != null) {
                        if (!checkBox.isChecked()) {
                            checkBox.setChecked(true);
                            appAdapter.setCheckData(position, true);

                        } else {
                            checkBox.setChecked(false);
                            appAdapter.setCheckData(position, false);
                        }
                        actionMode.setTitle("已经选择" + appAdapter.getCheckData().size() + "项");
                    }

                    return;
                }

                //之前的单击事件

                AppBaseInfo appBaseInfo = (AppBaseInfo) adapter.getData().get(position);
                File soc = new File(appBaseInfo.getPath());
                File tag = new File(OtherUtils.getExportDirectory(context), getFileNameRule(appBaseInfo) + ".apk");


                String[] items = new String[]{"打开", "提取", "发送", "详情", "卸载"};

                if (AppUtils.isSystemApplication(context, getPackageName()) || OtherUtils.getImplementWay(context) != 1) {
                    items = new String[]{"打开", "提取", "发送", "详情", "卸载", appBaseInfo.isFreeze() ? "启用" : "停用"};
                }

                AlertDialog alertDialog = new MaterialAlertDialogBuilder(this, com.dabai.uitools.R.style.DBTheme_Dialog_RoundTheme)
                        .setItems(items, (dialog, which) -> {
                            switch (which) {
                                case 5:

                                    if (appBaseInfo.isFreeze()) {

                                        new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                                                .setTitle("提示")
                                                .setMessage("是否启用 " + appBaseInfo.getName() + " ?")
                                                .setPositiveButton("启用", (dialog12, which12) -> new Thread(() -> {

                                                    if (OtherUtils.getImplementWay(context) == 1) {
                                                        packageManager.setApplicationEnabledSetting(appBaseInfo.getPackageName(), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
                                                    } else if (OtherUtils.getImplementWay(context) == 2) {
                                                        ShellUtils.enableApp(appBaseInfo.getPackageName());
                                                    } else if (OtherUtils.getImplementWay(context) == 3) {
                                                        ShizukuShell.getInstance().exec(new Shell.Command(
                                                                "pm enable ", appBaseInfo.getPackageName()));
                                                    }
                                                    runOnUiThread(() -> {
                                                        DBToast.showText(context, "操作完成!", true);
                                                        refreshList("");
                                                    });
                                                }).start()).setNeutralButton("取消", null)
                                                .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                                    } else {

                                        new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                                                .setTitle("提示")
                                                .setMessage("是否停用 " + appBaseInfo.getName() + " ?")
                                                .setPositiveButton("停用", (dialog12, which12) -> new Thread(() -> {

                                                    if (OtherUtils.getImplementWay(context) == 1) {
                                                        packageManager.setApplicationEnabledSetting(appBaseInfo.getPackageName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
                                                    } else if (OtherUtils.getImplementWay(context) == 2) {
                                                        ShellUtils.disableApp(appBaseInfo.getPackageName());
                                                    } else if (OtherUtils.getImplementWay(context) == 3) {
                                                       ShizukuShell.getInstance().exec(new Shell.Command(
                                                                "pm disable-user ", appBaseInfo.getPackageName()));

                                                    }
                                                    runOnUiThread(() -> {
                                                        DBToast.showText(context, "操作完成!", true);
                                                        refreshList("");
                                                    });
                                                }).start()).setNeutralButton("取消", null)
                                                .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                                    }

                                    break;
                                case 0:
                                    try {
                                        AppUtils.openApp(context, appBaseInfo.getPackageName());
                                    } catch (Exception e) {
                                        DBToast.showText(context, "打开失败!", false);
                                    }
                                    break;
                                case 1:

                                    TipAlertDialog.getInstance(context).showTipLayout("正在提取软件包..");

                                    new Thread(() -> {

                                        boolean isOk;
                                        if (
                                                SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("skipAlreadyExist", true)
                                                        && tag.exists()) {
                                            isOk = true;
                                        } else {
                                            isOk = FileUtils.copyFile(soc, tag, true);
                                        }

                                        runOnUiThread(() -> {

                                            DBToast.showMethodsFeedbackText(context, isOk, appBaseInfo.getName() + " 提取成功!", appBaseInfo.getName() + " 提取失败!");
                                            TipAlertDialog.getInstance(context).hideTipLayout();

                                        });
                                    }).start();

                                    break;
                                case 2:

                                    TipAlertDialog.getInstance(context).showTipLayout("正在提取软件包..");
                                    new Thread(() -> {

                                        boolean isOk;
                                        if (
                                                SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("skipAlreadyExist", true)
                                                        && tag.exists()) {
                                            isOk = true;
                                        } else {
                                            isOk = FileUtils.copyFile(soc, tag, true);
                                        }

                                        if (isOk) {
                                            ShareUtils.shareFile(context, tag, "*/*");
                                        }
                                        runOnUiThread(() -> TipAlertDialog.getInstance(context).hideTipLayout());
                                    }).start();
                                    break;
                                case 3:

                                    Intent intent = new Intent(this, AppDetailsActivity.class);
                                    intent.putExtra("packageName", appBaseInfo.getPackageName());
                                    startActivity(intent);

                                    break;
                                case 4:

                                    appBaseInflows = new ArrayList<>();
                                    appBaseInflows.add(appBaseInfo);

                                    if (AppUtils.isSystemApplication(context, appBaseInfo.getPackageName())) {
                                        new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                                                .setTitle("警告")
                                                .setMessage("系统软件卸载后可能导致系统崩溃,确定卸载吗?")
                                                .setPositiveButton("确定", (dialog1, which1) -> OtherUtils.uninstallApks(MainActivity.this, appBaseInflows, new OnCompleteListener() {
                                                    @Override
                                                    public void start() {

                                                    }
                                                    @Override
                                                    public void complete() {
                                                        refreshList("");
                                                    }
                                                    @Override
                                                    public void progress(int progress) {
                                                    }
                                                })).setNeutralButton("取消", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                                    } else {
                                        OtherUtils.uninstallApks(MainActivity.this, appBaseInflows, new OnCompleteListener() {
                                            @Override
                                            public void start() {

                                            }
                                            @Override
                                            public void complete() {
                                                refreshList("");
                                            }

                                            @Override
                                            public void progress(int progress) {

                                            }
                                        });

                                    }
                                    break;
                            }
                        }).show();


                alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            });

            runOnUiThread(() -> {
                amb.recyclerView.setAdapter(appAdapter);
                TipAlertDialog.getInstance(context).hideTipLayout();
                setTitle("应用程序管理(" + appAdapter.getData().size() + ")");
            });

            appAdapter.setOnItemLongClickListener((adapter, view, position) -> {

                //长按进去 多选模式
                if (!appAdapter.isSelect()) {
                    if (actionMode == null) {
                        actionMode = startActionMode(actionCallback);
                    }
                    appAdapter.setSelect(true);
                    appAdapter.showAllCheckBox();

                    appAdapter.setCheckView(position, true);
                    appAdapter.setCheckData(position, true);

                    actionMode.setTitle("已经选择" + appAdapter.getCheckData().size() + "项");

                }

                return true;
            });

        }).start();

    }




    /**
     * ActionMode 回调
     */
    private ActionMode actionMode;
    private final ActionMode.Callback actionCallback = new ActionMode.Callback() {

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            mode.setTitle("多选模式");
            amb.swipeRefreshLayout.setEnabled(false);
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            //销毁时清空 所有数据
            appAdapter.setSelect(false);
            actionMode = null;
            appAdapter.hideAllCheckBox();

            amb.swipeRefreshLayout.setEnabled(true);
        }

        // 从XML菜单中加载菜单
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.action_main, menu);
            return true;
        }


        public void setProgress(int pro) {
            if (
                    SharedPreferencesUtils.getDefaultSharedPreferences(context)
                            .getBoolean("notificationBarSchedule", true)) {
                if (notification != null) {
                    // 设置新的百分比
                    notification.setContentText(pro + "%").
                            setProgress(100, pro, false);
                    // 发送通知
                    notificationManager.notify(100, notification.build());
                }
            }
        }

        public void setProgressComplete(String content) {
            if (
                    SharedPreferencesUtils.getDefaultSharedPreferences(context)
                            .getBoolean("notificationBarSchedule", true)) {
                if (notification != null) {

                    notification.setContentText(content)
                            .setProgress(0, 0, false);
                    notificationManager.notify(100, notification.build());
                }
            }
        }

        public void setProgressContent(String content) {
            if (
                    SharedPreferencesUtils.getDefaultSharedPreferences(context)
                            .getBoolean("notificationBarSchedule", false)) {
                if (notification != null) {
                    notification.setContentText(content);
                    notificationManager.notify(100, notification.build());
                }
            }
        }


        // 菜单被点击
        @SuppressLint("NonConstantResourceId")
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

            appBaseInflows = appAdapter.getCheckAppInflows();

            switch (item.getItemId()) {
                case R.id.selectAll:
                    appAdapter.selectAllCheckBox();
                    actionMode.setTitle("已经选择" + appAdapter.getCheckData().size() + "项");
                    break;
                case R.id.cancelAll:
                    appAdapter.cancelSelectAllCheckBox();
                    actionMode.setTitle("已经选择" + appAdapter.getCheckData().size() + "项");
                    break;
                case R.id.inverseSelect:
                    appAdapter.inverseSelectAllCheckBox();
                    actionMode.setTitle("已经选择" + appAdapter.getCheckData().size() + "项");
                    break;
                case R.id.extract:

                    if (appAdapter.getCheckDataSize() <= 0) {
                        DBToast.showYellowToast(context, "未选中任何列表项!");
                        return true;
                    }

                    new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                            .setTitle("提示")
                            .setMessage("确定提取共 " + appAdapter.getCheckDataSize() + " 个程序嘛? 总体积约为 " + FileUtils.formatFileSizeToString(appAdapter.getCheckAppSize()))
                            .setPositiveButton("确定", (dialog, which) -> {

                                actionMode.finish();
                                TipAlertDialog.getInstance(context).showTipLayout("正在提取软件包");

                                setProgress(0);

                                new Thread(() -> {

                                    for (int i = 0; i < appBaseInflows.size(); i++) {

                                        AppBaseInfo appBaseInfo = appBaseInflows.get(i);

                                        File soc = new File(appBaseInfo.getPath());
                                        File tag = new File(OtherUtils.getExportDirectory(context), getFileNameRule(appBaseInfo) + ".apk");

                                        int extractProgress = (int) ((float) i / (float) appBaseInflows.size() * 100);
                                        runOnUiThread(() -> {

                                            TipAlertDialog.getInstance(context).showTipLayout("正在提取 " + appBaseInfo.getName() + "(" + FileUtils.getFileSizeToString(soc) + ")" + "\n总进度:" + (extractProgress) + "%");
                                            setProgress(extractProgress);

                                        });

                                        boolean isOk;
                                        if (
                                                SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("skipAlreadyExist", true)
                                                        && tag.exists()) {
                                            isOk = true;
                                        } else {
                                            isOk = FileUtils.copyFile(soc, tag, true);
                                        }

                                        if (!isOk) {
                                            runOnUiThread(() -> DBToast.showText(context, appBaseInfo.getName() + " 提取失败!", false));
                                        }
                                    }


                                    runOnUiThread(() -> {
                                        DBToast.showText(context, "批量提取完毕!", true);
                                        TipAlertDialog.getInstance(context).hideTipLayout();
                                        setProgressComplete("批量提取完毕!");
                                    });

                                }).start();

                            }).setNeutralButton("取消", null)
                            .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);


                    break;
                case R.id.send:

                    if (appAdapter.getCheckDataSize() <= 0) {
                        DBToast.showYellowToast(context, "未选中任何列表项!");
                        return true;
                    }


                    new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                            .setTitle("提示")
                            .setMessage("确定发送共 " + appAdapter.getCheckDataSize() + " 个程序嘛? 总体积约为 " + FileUtils.formatFileSizeToString(appAdapter.getCheckAppSize()))
                            .setPositiveButton("确定", (dialog, which) -> {

                                actionMode.finish();

                                TipAlertDialog.getInstance(context).showTipLayout("正在提取软件包");
                                ArrayList<File> shareList = new ArrayList<>();

                                setProgress(0);
                                setProgressContent("正在提取软件包...");
                                new Thread(() -> {

                                    for (int i = 0; i < appBaseInflows.size(); i++) {

                                        AppBaseInfo appBaseInfo = appBaseInflows.get(i);

                                        File soc = new File(appBaseInfo.getPath());
                                        File tag = new File(OtherUtils.getExportDirectory(context), getFileNameRule(appBaseInfo) + ".apk");

                                        int extractProgress = (int) ((float) i / (float) appBaseInflows.size() * 100);
                                        runOnUiThread(() -> {
                                            TipAlertDialog.getInstance(context).showTipLayout("正在提取 " + appBaseInfo.getName() + "(" + FileUtils.getFileSizeToString(soc) + ")" + "\n总进度:" + (extractProgress) + "%");
                                            setProgress(extractProgress);
                                        });

                                        boolean isOk;
                                        if (
                                                SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("skipAlreadyExist", true)
                                                        && tag.exists()) {
                                            isOk = true;
                                        } else {
                                            isOk = FileUtils.copyFile(soc, tag, true);
                                        }

                                        if (!isOk) {
                                            runOnUiThread(() -> DBToast.showText(context, appBaseInfo.getName() + " 提取失败!", false));
                                        } else {
                                            shareList.add(tag);
                                        }

                                    }

                                    //压缩打包,再发送出去.再清除缓存

                                    ShareUtils.shareMultipleFile(context, "*/*", shareList);

                                    runOnUiThread(() -> {
                                        DBToast.showText(context, "批量提取完毕,并调用分享!", true);
                                        TipAlertDialog.getInstance(context).hideTipLayout();
                                        setProgressComplete("批量提取完毕,并调用分享!");
                                    });

                                }).start();

                            }).setNeutralButton("取消", null)
                            .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                    break;
                case R.id.delete:

                    if (appAdapter.getCheckDataSize() <= 0) {
                        DBToast.showYellowToast(context, "未选中任何列表项!");
                        return true;
                    }

                    OtherUtils.uninstallApks(MainActivity.this, appBaseInflows, new OnCompleteListener() {
                        @Override
                        public void start() {
                            actionMode.finish();
                            setProgress(0);
                            setProgressContent("正在批量卸载...");
                        }

                        @Override
                        public void complete() {
                            setProgressComplete("全部卸载完成!");
                            refreshList("");
                        }

                        @Override
                        public void progress(int progress) {
                            setProgress(progress);
                        }
                    });
                    break;
                default:
                    break;
            }

            return true;
        }
    };


    /**
     * 获得文件名规则
     *
     * @param appBaseInfo 应用基本信息
     * @return {@link String}
     */
    public String getFileNameRule(AppBaseInfo appBaseInfo) {

        String rule = SharedPreferencesBasicUse.getString("extractNamingRules", "&n_&vn_&vc");

        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(
                    appBaseInfo.getPackageName(), 0);
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                rule = rule
                        //minSdkVersion
                        .replaceAll("&msv", applicationInfo.minSdkVersion + "");
            }
            rule = rule
                    //targetSdkVersion
                    .replaceAll("&tsv", applicationInfo.targetSdkVersion + "")
                    //uid
                    .replaceAll("&uid", applicationInfo.uid + "");

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return rule
                //应用名
                .replaceAll("&n", appBaseInfo.getName())
                //版本名
                .replaceAll("&vn", appBaseInfo.getVersion())
                //版本代码
                .replaceAll("&vc", appBaseInfo.getVersionCode())
                //包名
                .replaceAll("&pn", appBaseInfo.getPackageName());
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                DBToast.showYellowToast(getApplicationContext(), "再按一次退出程序!");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.search) {
            searchFragment.show(getSupportFragmentManager(),SearchFragment.TAG);
            return true;
        } else if (itemId == R.id.setting) {
            ActivityUtils.startActivity(this, SettingsActivity.class);
            return true;
        } else if (itemId == R.id.widgets) {
            ActivityUtils.startActivity(this, SmallProgramActivity.class);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 获得出口目录
     *
     * @return {@link File}
     */
    public static File getExportDirectory() {
        return FileUtils.getDir(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "AppManager"));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        TipAlertDialog.destroyTipLayout();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 301) {
                if (data != null) {


                }
            }
        }

    }

}